<script lang="ts" setup>
// 模块引入
import Account from "../base/AccountStore";
import { useRouter } from "vue-router";
import { PageName } from "../base/Router";
import { ref, onMounted, watch } from "vue"; // 添加 watch 导入
import { ElMessage } from "element-plus";

let router = useRouter();
let account = Account();
// 绑定到搜索栏的属性
let searchText = ref("");

// 全部分类弹窗控制
let showAllCategories = ref(false);
// 分类数据 - 从商品页面同步
let categoryList = ref<
  Array<{ id: number; name: string; description?: string }>
>([]);

// 用户头像响应式数据
let userAvatar = ref("");

// 监听账户信息变化，同步头像
watch(
  () => account.info,
  (newInfo) => {
    if (newInfo && newInfo.avatar) {
      userAvatar.value = newInfo.avatar;
    } else {
      userAvatar.value = "";
    }
  },
  { immediate: true, deep: true }
);

// 登出方法
function logout() {
  account.logout();
  ElMessage.success("已退出登录");
}

// 处理用户下拉菜单命令
function handleUserMenu(command: string) {
  if (command === "logout") {
    logout();
  } else if (command === "profile") {
    // 跳转到个人中心页面
    if (!account.isLogin) {
      ElMessage.warning("请先登录");
      router.push({ name: PageName.login });
      return;
    }
    router.push({
      name: "profile",
    });
  }
}

// 跳转到购物车的方法
function goShopCar() {
  if (!account.isLogin) {
    ElMessage.warning("请先登录后再查看购物车");
    router.push({ name: PageName.login });
    return;
  }
  router.push({
    name: "shopCar",
  });
}

// 跳转订单列表页面
function goOrder() {
  if (!account.isLogin) {
    ElMessage.warning("请先登录后再查看订单");
    router.push({ name: PageName.login });
    return;
  }
  router.push({
    name: "order",
  });
}

function toSearch() {
  if (searchText.value.length > 0) {
    console.log(searchText.value);
    router.push({
      name: "search",
      params: {
        keyword: searchText.value,
      },
    });
  }
}

// 返回首页的方法
function goHome() {
  router.push({
    name: "home",
  });
}

// 跳转到评价列表页面（所有评价记录）
function goEvaluation() {
  if (!account.isLogin) {
    ElMessage.warning("请先登录后再查看评价");
    router.push({ name: PageName.login });
    return;
  }
  router.push({
    name: "evaluationList",
  });
}

// 打开全部分类弹窗
function openAllCategories() {
  showAllCategories.value = true;
  // 尝试从商品页面获取分类数据
  syncCategoryData();
}

// 同步分类数据
function syncCategoryData() {
  // 方法1：从localStorage或全局状态获取
  const storedCategories = localStorage.getItem("categoryList");
  if (storedCategories) {
    categoryList.value = JSON.parse(storedCategories);
    return;
  }
}

// 定位到指定分类
function scrollToCategory(categoryId: number) {
  showAllCategories.value = false;

  // 给页面一点时间关闭弹窗
  setTimeout(() => {
    const element = document.getElementById(`category-${categoryId}`);
    if (element) {
      // 获取主导航栏高度，用于计算滚动偏移
      const headerHeight = 80; // 现在只需要主导航栏的高度80px
      const elementPosition =
        element.getBoundingClientRect().top + window.pageYOffset;
      const offsetPosition = elementPosition - headerHeight - 20; // 额外20px的间距

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth",
      });
    } else {
      // 如果元素不存在，可能是商品页面还未加载对应分类
      console.warn(`未找到分类元素: category-${categoryId}`);
    }
  }, 300);
}

// 用户头像点击事件
function handleUserAvatarClick() {
  if (!account.isLogin) {
    ElMessage.warning("请先登录");
    router.push({ name: PageName.login });
  }
}

// 消息通知点击事件
function handleNotificationClick() {
  if (!account.isLogin) {
    ElMessage.warning("请先登录后再查看消息");
    router.push({ name: PageName.login });
    return;
  }
  // 消息通知逻辑
  console.log("查看消息通知");
}

// 组件挂载时初始化
onMounted(() => {
  // 初始化时尝试获取分类数据
  syncCategoryData();

  // 初始化用户头像
  if (account.info?.avatar) {
    userAvatar.value = account.info.avatar;
  }
});
</script>

<template>
  <!-- 顶部信息栏 -->
  <div class="vmall-topbar">
    <div class="vmall-container">
      <div class="vmall-topbar-left">
        <!-- 导航菜单移到这里 -->
        <div class="vmall-nav-menu-mini">
          <a href="#" class="vmall-link mini-nav" @click.prevent="goHome"
            >首页</a
          >
          <a href="#" class="vmall-link mini-nav" @click.prevent=""
            >消费者业务网站</a
          >
          <a href="#" class="vmall-link mini-nav" @click.prevent="">优购码</a>
          <a href="#" class="vmall-link mini-nav" @click.prevent="">企业商用</a>
          <a href="#" class="vmall-link mini-nav" @click.prevent=""
            >Select Region</a
          >
        </div>
      </div>
      <div class="vmall-topbar-right">
        <a href="#" class="vmall-link">百强企业 品质保证</a>
        <span class="vmall-separator">|</span>
        <a href="#" class="vmall-link">7天退货 15天换货</a>
        <span class="vmall-separator">|</span>
        <a href="#" class="vmall-link">官方售后 全国联保</a>
      </div>
    </div>
  </div>

  <!-- 主导航栏 -->
  <div class="vmall-sticky-header">
    <div class="vmall-main-header">
      <div class="vmall-container">
        <!-- 左侧Logo和全部分类区域 -->
        <div class="vmall-left-area">
          <!-- Logo区域 -->
          <div class="vmall-logo-area" @click="goHome">
            <span class="vmall-logo-text">ApexStore</span>
          </div>

          <!-- 全部分类按钮 -->
          <div class="vmall-all-category-btn" @click="openAllCategories">
            <el-icon><Menu /></el-icon>
            <span>全部分类</span>
          </div>
        </div>

        <!-- 主导航栏中间区域 -->
        <div class="vmall-nav-center">
          <!-- 保留空白区域，使布局更均衡 -->
        </div>

        <!-- 右侧用户区域 -->
        <div class="vmall-user-area">
          <!-- 搜索框 -->
          <div class="vmall-search-box">
            <el-input
              v-model="searchText"
              placeholder="搜索感兴趣的商品"
              style="width: 300px"
              prefix-icon="Search"
              @keyup.enter="toSearch"
            >
              <template #append>
                <el-button
                  type="primary"
                  style="background-color: #e02020; border-color: #e02020"
                  @click="toSearch"
                  >搜索</el-button
                >
              </template>
            </el-input>
          </div>

          <!-- 用户功能图标 -->
          <div class="vmall-user-icons">
            <!-- 购物车图标 -->
            <el-tooltip content="购物车" placement="bottom">
              <div class="vmall-icon-item" @click="goShopCar">
                <el-icon><ShoppingCart /></el-icon>
              </div>
            </el-tooltip>

            <el-tooltip content="消息通知" placement="bottom">
              <div class="vmall-icon-item" @click="handleNotificationClick">
                <el-icon><Bell /></el-icon>
              </div>
            </el-tooltip>

            <el-tooltip content="我的订单" placement="bottom">
              <div class="vmall-icon-item" @click="goOrder">
                <el-icon><Briefcase /></el-icon>
              </div>
            </el-tooltip>

            <el-tooltip content="我的评价" placement="bottom">
              <div class="vmall-icon-item" @click="goEvaluation">
                <el-icon><Star /></el-icon>
              </div>
            </el-tooltip>

            <!-- 用户头像 -->
            <el-dropdown v-if="account.isLogin" @command="handleUserMenu">
              <div class="vmall-user-avatar">
                <el-avatar
                  :src="userAvatar"
                  :style="{
                    backgroundColor: userAvatar ? 'transparent' : '#e02020',
                    objectFit: 'cover',
                  }"
                  fit="cover"
                >
                  {{ account.displayAvatar }}
                </el-avatar>
                <span class="vmall-username">{{
                  account.displayUsername
                }}</span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile"
                    >个人中心</el-dropdown-item
                  >
                  <el-dropdown-item command="logout" divided
                    >注销</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <div
              v-else
              class="vmall-user-avatar"
              @click="handleUserAvatarClick"
            >
              <el-avatar style="background-color: #909399">{{
                account.displayAvatar
              }}</el-avatar>
              <span class="vmall-username">{{ account.displayUsername }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 全部分类弹窗 -->
  <el-dialog
    v-model="showAllCategories"
    title="全部分类"
    width="800px"
    class="vmall-category-dialog"
    :before-close="() => (showAllCategories = false)"
  >
    <div class="vmall-category-grid" v-if="categoryList.length > 0">
      <div
        v-for="category in categoryList"
        :key="category.id"
        class="vmall-category-grid-item"
        @click="scrollToCategory(category.id)"
      >
        <div class="vmall-category-grid-name">{{ category.name }}</div>
        <div class="vmall-category-grid-desc">
          {{ category.description || "精选商品" }}
        </div>
      </div>
    </div>
    <div v-else class="vmall-category-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载分类中...</span>
    </div>
  </el-dialog>

  <!-- 主流功能区 -->
  <div class="main-content">
    <div class="vmall-container">
      <router-view :key="router.currentRoute.value.fullPath"></router-view>
    </div>
  </div>
</template>

<style scoped>
/* 华为商城风格样式 */
.vmall-container {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 顶部信息栏 */
.vmall-topbar {
  background-color: rgb(0, 0, 0);
  height: 36px;
  line-height: 36px;
  font-size: 12px;
  border-bottom: 1px solid #e5e5e5;
  position: relative;
  z-index: 999;
}

.vmall-topbar-left,
.vmall-topbar-right {
  display: flex;
  align-items: center;
}

.vmall-sticky-header {
  position: sticky;
  top: 0;
  width: 100%;
  z-index: 1000;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 用户头像区域 */
.vmall-user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.vmall-user-avatar:hover {
  background-color: #f5f5f5;
}

.vmall-username {
  font-size: 14px;
  color: #333;
}

:deep(.el-avatar) {
  flex-shrink: 0;
}

/* 主内容区域  */
.main-content {
  width: 100%;
  min-height: calc(100vh - 80px);
  background-color: #f5f5f5;
}

.main-content .vmall-container {
  display: block;
  padding: 20px 0;
}

/* 迷你导航菜单样式 */
.vmall-nav-menu-mini {
  display: flex;
  align-items: center;
  gap: 0;
}

.mini-nav {
  padding: 0 15px;
  position: relative;
  cursor: pointer;
}

.mini-nav:not(:last-child)::after {
  content: "|";
  position: absolute;
  right: 0;
  color: #e0e0e0;
}

.vmall-link {
  color: rgba(255, 255, 255, 0.6);
  text-decoration: none;
  padding: 0 10px;
  transition: color 0.3s;
  cursor: pointer;
}

.vmall-link:hover {
  color: #fff;
}

.vmall-separator {
  color: #e0e0e0;
  margin: 0 2px;
}

/* 主导航栏 */
.vmall-main-header {
  background-color: #fff;
  padding-top: 10px;
  height: 55px;
  border-bottom: 2px solid #e02020;
}

/* 左侧区域 */
.vmall-left-area {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* Logo区域 */
.vmall-logo-area {
  cursor: pointer;
}

.vmall-logo-text {
  font-size: 28px;
  font-weight: bold;
  color: #e02020;
}

/* 全部分类按钮 */
.vmall-all-category-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-top: 8px;
  color: #000000da;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  border: none;
}

.vmall-all-category-btn:hover {
  color: #c61818;
  transform: translateY(-2px);
}

/* 导航菜单 */
.vmall-nav-center {
  flex: 1;
  margin-left: 60px;
}

/* 用户区域 */
.vmall-user-area {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 搜索框 */
.vmall-search-box {
  position: relative;
}

/* 用户图标 */
.vmall-user-icons {
  display: flex;
  align-items: center;
  gap: 20px;
}

.vmall-icon-item {
  cursor: pointer;
  font-size: 20px;
  color: #666;
  transition: color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  border-radius: 4px;
}

.vmall-icon-item:hover {
  color: #e02020;
  background-color: #f5f5f5;
}

/* 用户头像 */
.vmall-user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.vmall-user-avatar:hover {
  background-color: #f5f5f5;
}

.vmall-username {
  font-size: 14px;
  color: #333;
}

/* 全部分类弹窗样式 */
.vmall-category-dialog .el-dialog {
  border-radius: 12px;
}

.vmall-category-dialog .el-dialog__header {
  border-bottom: 1px solid #e5e5e5;
  padding: 20px;
}

.vmall-category-dialog .el-dialog__body {
  padding: 20px;
}

.vmall-category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.vmall-category-grid-item {
  padding: 10px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.vmall-category-grid-item:hover {
  border-color: #e02020;
  background: rgba(224, 32, 32, 0.05);
  transform: translateY(-2px);
}

.vmall-category-grid-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.vmall-category-grid-desc {
  font-size: 12px;
  color: #666;
}

.vmall-category-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 40px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1220px) {
  .vmall-container {
    width: 95%;
  }

  .vmall-nav-menu {
    margin-left: 30px;
  }

  .el-menu-item {
    padding: 0 15px;
    font-size: 14px;
  }

  .vmall-search-box .el-input {
    width: 250px;
  }

  .vmall-category-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .vmall-user-icons {
    gap: 15px;
  }
}

@media (max-width: 1024px) {
  .vmall-all-category-btn {
    padding: 10px 16px;
    font-size: 13px;
  }

  .vmall-logo-text {
    font-size: 24px;
  }

  .vmall-category-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .vmall-user-icons {
    gap: 12px;
  }

  .vmall-search-box .el-input {
    width: 220px;
  }
}

@media (max-width: 900px) {
  .vmall-left-area {
    gap: 15px;
  }

  .vmall-all-category-btn {
    padding: 8px 12px;
    font-size: 12px;
  }

  .vmall-logo-text {
    font-size: 20px;
  }

  .vmall-search-box .el-input {
    width: 200px;
  }

  .vmall-category-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .vmall-user-icons {
    gap: 10px;
  }

  .vmall-username {
    display: none;
  }
}

@media (max-width: 768px) {
  .vmall-all-category-btn span {
    display: none;
  }

  .vmall-all-category-btn {
    padding: 10px;
  }

  .vmall-category-grid {
    grid-template-columns: 1fr;
  }

  .vmall-user-icons {
    gap: 8px;
  }

  .vmall-search-box .el-input {
    width: 160px;
  }

  .vmall-icon-item {
    padding: 6px;
  }
}

@media (max-width: 640px) {
  .vmall-user-area {
    gap: 10px;
  }

  .vmall-search-box .el-input {
    width: 140px;
  }

  .vmall-user-icons {
    gap: 6px;
  }

  .vmall-icon-item {
    padding: 4px;
  }
}
</style>